﻿#include "stdafx.h"
#include "CallGen.h"
#include "StringLiteGen.h"
#include "FunctionInstance.h"
#include "ClassInstanceType.h"
#include "utility.h"

using namespace llvm;
Value * CallGen::generateCode(Module *m, Function *func, llvm::IRBuilder<>&builder)
{
	Function *f=function->generateCode(m, builder.getContext());

	std::vector< llvm::Value* > a;
	auto *argIterator=f->arg_begin();
	for (auto *i : params) {
		Value* v = i->generateCode(m, func, builder);

		bool isPoint = ClassInstanceType::isClass(i->type) || dynamic_cast<StringLiteGen*>(i);

		if (!v)
			v = ConstantInt::getNullValue(argIterator->getType());

		if (!isPoint) {									// 写入指针
			v = load(builder, v);
		}
		if (argIterator == f->arg_end()) {	// 可变参数
			a.push_back(v);
		}
		else {
			a.push_back(try_cast(builder, argIterator->getType(), v));
			argIterator++;
		}
	}

	return builder.CreateCall(f, a);
}
